import bpy
from bpy.app import timers

from . import QueueUtils
from .log import log


class RenderQueue:
    blend_file = ''
    init = [False]

    @staticmethod
    def render_queue():
        """渲染队列"""
        pref = QueueUtils.pref_()

        if not RenderQueue.init[0] and pref:
            pref.stop_all_render()  # 不允许进入blender就进行渲染
            RenderQueue.init[0] = True
            return

        if pref and (not pref.render_in_item) and pref.render_in_queue_items:
            # 如果没有渲染项并且有渲染队列
            queues = pref.render_in_queue_items
            queues[0].render()

        elif pref and pref.render_in_item:
            # 更新渲染进度
            area = bpy.context.area
            if area:
                area.tag_redraw()
            pref.render_in_item.update_render_progress()


class TIMERS:
    @staticmethod
    def timers_update():
        try:
            if not bpy.app.background:
                RenderQueue.render_queue()
        except Exception as e:
            log.debug(f'timers_update error {e.args}')
            import traceback
            traceback.print_exc()
        return 1 / 60


def register():
    timers.register(TIMERS.timers_update, persistent=True)


def unregister():
    pref = QueueUtils.pref_()
    pref.stop_all_render()

    if timers.is_registered(TIMERS.timers_update):
        timers.unregister(TIMERS.timers_update)
